package com.robot.coupon.service;

import com.robot.coupon.dao.CouponDao;
import com.robot.coupon.pojo.Coupon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import util.IdWorker;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * coupon服务层
 *
 * @author wuyunbin
 */
@Service
public class CouponService {
    @Autowired
    private CouponDao couponDao;

    @Autowired
    private IdWorker idWorker;

    /**
     * 查询全部列表
     *
     * @return
     */
    public List<Coupon> findAll() {
        return couponDao.findAll();
    }


    /**
     * 条件查询+分页
     *
     * @param whereMap
     * @param page
     * @param size
     * @return
     */
    public Page<Coupon> findSearch(Map whereMap, int page, int size) {
        Specification<Coupon> specification = createSpecification(whereMap);
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        return couponDao.findAll(specification, pageRequest);
    }


    /**
     * 条件查询
     *
     * @param whereMap
     * @return
     */
    public List<Coupon> findSearch(Map whereMap) {
        Specification<Coupon> specification = createSpecification(whereMap);
        return couponDao.findAll(specification);
    }

    /**
     * 根据ID查询实体
     *
     * @param id
     * @return
     */
    public Coupon findById(String id) {
        return couponDao.findById(id).orElse(null);
    }

    /**
     * 增加
     *
     * @param coupon
     */
    public void add(Coupon coupon) {
        //雪花分布式ID生成器
        coupon.setId(idWorker.nextId() + "");
        coupon.setStatus("0");
        LocalDateTime now = LocalDateTime.now();
        coupon.setCreatedAt(now);
        coupon.setUpdatedAt(now);
        couponDao.save(coupon);
    }

    /**
     * 修改
     *
     * @param coupon
     */
    public void update(Coupon coupon) {
        couponDao.save(coupon);
    }

    /**
     * 删除
     *
     * @param id
     */
    public void deleteById(String id) {
        couponDao.deleteById(id);
    }

    /**
     * 动态条件构建
     *
     * @param searchMap
     * @return
     */
    private Specification<Coupon> createSpecification(Map searchMap) {
        return new Specification<Coupon>() {
            @Override
            public Predicate toPredicate(Root<Coupon> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();
                // 优惠券id
                String id = "id";
                if (searchMap.get(id) != null && !"".equals(searchMap.get(id))) {
                    predicateList.add(cb.like(root.get(id).as(String.class), "%" + (String) searchMap.get(id) + "%"));
                }
                // 会员id
                String memberId = "memberId";
                if (searchMap.get(memberId) != null && !"".equals(searchMap.get(memberId))) {
                    predicateList.add(cb.like(root.get(memberId).as(String.class), "%" + (String) searchMap.get(memberId) + "%"));
                }
                // 商家id
                String companyId = "companyId";
                if (searchMap.get(companyId) != null && !"".equals(searchMap.get(companyId))) {
                    predicateList.add(cb.like(root.get(companyId).as(String.class), "%" + (String) searchMap.get(companyId) + "%"));
                }
                // 店铺id
                String storeId = "storeId";
                if (searchMap.get(storeId) != null && !"".equals(searchMap.get(storeId))) {
                    predicateList.add(cb.like(root.get(storeId).as(String.class), "%" + (String) searchMap.get(storeId) + "%"));
                }
                // 店铺名字
                String storeName = "storeName";
                if (searchMap.get(storeName) != null && !"".equals(searchMap.get(storeName))) {
                    predicateList.add(cb.like(root.get(storeName).as(String.class), "%" + (String) searchMap.get(storeName) + "%"));
                }
                // 使用条件
                String usageCondition = "usageCondition";
                if (searchMap.get(usageCondition) != null && !"".equals(searchMap.get(usageCondition))) {
                    predicateList.add(cb.like(root.get(usageCondition).as(String.class), "%" + (String) searchMap.get(usageCondition) + "%"));
                }
                // 状态 0-未使用 1-已使用 2-已过期
                String status = "status";
                if (searchMap.get(status) != null && !"".equals(searchMap.get(status))) {
                    predicateList.add(cb.like(root.get(status).as(String.class), "%" + (String) searchMap.get(status) + "%"));
                }
                //剔除软删除数据
                String deletedAt = "deletedAt";
                predicateList.add(cb.equal(root.get(deletedAt), cb.nullLiteral(Date.class)));

                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
    }

    /**
     * 根据会员ID查找该会员名下的所有优惠券
     *
     * @param memberId
     * @return
     */
    public Page<Coupon> findAllByMemberId(String memberId, int page, int rows) {
        Pageable pageable = PageRequest.of(page - 1, rows);
        return couponDao.findAllByMemberId(memberId, pageable);
    }

    /**
     * 根据会员ID查找该会员名下特定状态的所有优惠券
     *
     * @param memberId
     * @param status
     * @param page
     * @param rows
     * @return
     */
    public Page<Coupon> findAllByMemberIdAndStatus(String memberId, String status, int page, int rows) {
        Pageable pageable = PageRequest.of(page - 1, rows);
        return couponDao.findAllByMemberIdAndStatus(memberId, status, pageable);
    }

    /**
     * 根据会员ID查找该会员名下的某张优惠券
     *
     * @param id
     * @param memberId
     * @return
     */
    public Coupon findByIdAndMemberId(String id, String memberId) {
        return couponDao.findByIdAndMemberId(id, memberId);
    }
}
